<template>
  <div
    v-loading="loading"
    class="dashboard-container"
    element-loading-text="数据加载中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <!-- 顶部搜索区 -->
    <div class="header">
      <div class="title">项目管理系统数据分析</div>
      <div class="search-area">
        <span class="label">日期范围</span>
        <el-date-picker
          v-model="dayRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
        />
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="primary" @click="handleExport">excel导出</el-button>
      </div>
    </div>
    <!-- 创建一个固定的挂载点 -->
    <div id="date-picker-container" />

    <ul class="main-content">
      <!-- 左侧列 -->
      <li class="content-column">
        <div class="total-info">
          <div class="total-row">
            <div class="total-item">
              <div class="total-label">{{ year }}年合同总金额</div>
              <div class="total-value">
                <span class="number">{{
                  formatNumber((totalMoney / 10000).toFixed(2))
                }}</span>
                <span class="unit">万元</span>
              </div>
            </div>
            <div class="total-item">
              <div class="total-label">{{ year }}年合同总数量</div>
              <div class="total-value">
                <span class="number">{{ totalCount }}</span>
                <span class="unit">个</span>
              </div>
            </div>
          </div>
        </div>
        <!-- 执行部门对应合同金额 -->
        <div class="chart-box">
          <div class="chart-title">
            <i class="chart-icon" />
            执行部门合同金额
          </div>
          <div ref="departmentChart" class="chart department-chart" />
        </div>
        <!-- 项目领域对应合同金额 -->
        <div class="chart-box">
          <div class="chart-header">
            <div class="chart-title">
              <i class="chart-icon" />
              领域合同金额
            </div>
            <div class="total-amount">
              <span class="total-label">总额：</span>
              <div class="value-wrapper">
                <span class="total-value">{{ totalAreaMoney }}</span>
              </div>
            </div>
          </div>
          <div ref="areaChart" class="chart" />
        </div>
      </li>

      <!-- 中间列 -->
      <li class="content-column">
        <div class="chart-box">
          <div class="chart-title">
            <i class="chart-icon" />
            产品合同金额
          </div>
          <div ref="productChart" class="chart product-chart" />
        </div>
      </li>

      <!-- 右侧列 -->
      <li class="content-column">
        <!-- 项目金额预览和项目成本预览 -->
        <div class="charts-row">
          <div class="chart-box">
            <div class="chart-title">
              <i class="chart-icon" />
              合同金额
            </div>
            <div ref="allMoneyChart" class="chart" />
          </div>
          <div class="chart-box">
            <div class="chart-title">
              <i class="chart-icon" />
              项目成本
            </div>
            <div ref="costMoneyChart" class="chart" />
          </div>
        </div>

        <!-- 项目属性和存量类型 -->
        <div class="charts-row">
          <!-- <div class="chart-box">
            <div class="chart-title">
              <i class="chart-icon"></i>
              项目类型合同金额
            </div>
            <div ref="propertyChart" class="chart"></div>
          </div> -->

          <div class="chart-box">
            <div class="chart-title">
              <i class="chart-icon" />
              客户类型合同金额
            </div>
            <div ref="customerChart" class="chart" />
          </div>
          <div class="chart-box">
            <div class="chart-title">
              <i class="chart-icon" />
              存量类型合同金额
            </div>
            <div ref="stockChart" class="chart" />
          </div>
        </div>

        <!-- 客户类型和划转对象 (移动到这里) -->
        <div class="charts-row">
          <div class="chart-box">
            <div class="chart-title">
              <i class="chart-icon" />
              划转金额
            </div>
            <div ref="transferChart" class="chart" />
          </div>
        </div>

        <!-- 移动采购方式统计到这里 -->
        <div class="chart-box" style="height: 400px">
          <div class="chart-title">
            <i class="chart-icon" />
            采购方式统计
          </div>
          <div ref="projectFromChart" class="chart project-from-chart" />
        </div>
      </li>
    </ul>

    <!-- 修改为使用 el-table 的弹框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="`${currentName}详情`"
      width="80%"
      :append-to-body="true"
      center
      @close="handleDialogClose"
    >
      <div class="dialog-header">
        <el-button
          type="primary"
          size="small"
          @click="handleDetailExport"
        >excel导出</el-button>
      </div>
      <el-table
        v-if="currentItem && currentItem.lists"
        :data="currentItem.lists"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="projectNo"
          label="项目编号"
          width="120"
          align="center"
        />
        <el-table-column
          prop="pname"
          label="项目名称"
          show-overflow-tooltip
          min-width="150"
          align="center"
        />
        <el-table-column
          prop="salesman"
          label="负责人"
          width="100"
          align="center"
        />
        <el-table-column align="center" prop="money" label="金额" width="100">
          <template slot-scope="scope">
            {{ (scope.row.money / 10000).toFixed(2) + "万元" }}
          </template>
        </el-table-column>
        <!-- 根据图表类型显示不同的成本列 -->
        <el-table-column
          align="center"
          :prop="
            currentType === 1 || currentType === 6 || currentType === 9
              ? 'estimatedCost'
              : 'cost'
          "
          :label="
            currentType === 1 || currentType === 6 || currentType === 9
              ? '成本'
              : '项目成本'
          "
        />
        <el-table-column
          align="center"
          prop="customer"
          label="客户单位"
          min-width="130"
          show-overflow-tooltip
        />

        <template v-if="isTransferChart">
          <el-table-column
            prop="transferCompany"
            label="划转对象"
            width="120"
            align="center"
          />
          <el-table-column align="center" prop="transferMoney" label="划转金额">
            <template slot-scope="scope">
              {{ (scope.row.transferMoney / 10000).toFixed(2) + "万元" }}
            </template>
          </el-table-column>
        </template>
        <el-table-column
          align="center"
          prop="content"
          min-width="200"
          label="执行内容及要求"
          show-overflow-tooltip
        />
      </el-table>
    </el-dialog>

    <!-- 修改广告弹框 -->
    <el-dialog
      title="广告详细数据"
      :visible.sync="showAdvertDialog"
      :modal="false"
      width="90%"
      :append-to-body="true"
      center
    >
      <el-table
        :data="advertData"
        style="width: 100%"
        row-key="id"
        border
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
      >
        <el-table-column
          prop="projectNo"
          label="项目编号"
          width="150"
          align="center"
        />
        <el-table-column
          prop="pname"
          label="项目名称"
          min-width="150"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="salesman"
          label="负责人"
          width="100"
          align="center"
        />
        <el-table-column prop="money" label="金额" width="100" align="center">
          <template slot-scope="scope">
            {{ (scope.row.money / 10000).toFixed(2) + "万元" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="customer"
          label="客户单位"
          min-width="150"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="content"
          label="执行内容及要求"
          min-width="300"
          align="center"
          show-overflow-tooltip
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  selCustomerTypeMoneyListApi,
  selDepartmentMoneyListApi,
  selPlatformMoneyListApi,
  selProjectAreaMoneyListApi,
  selProjectFromAllMoneyListApi,
  selStockTypeMoneyListApi,
  dataExcelApi,
  projectDataApi,
  selMoneyAndCountApi,
  selProjectTypeAllMoneyListApi,
  selProjectTypeCostMoneyListApi,
  selTransferMoneyListApi
} from '@/api/data_board'
export default {
  name: 'DashboardData',
  data() {
    return {
      dayRange: [],
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > Date.now()
        }
      },
      charts: {},
      appendTo: null,
      customerChartOption: {},
      departmentChartOption: {},
      platformChartOption: {},
      areaChartOption: {},
      propertyChartOption: {},
      stockChartOption: {},
      totalMoney: 0,
      totalCount: 0,
      loading: true,
      dialogVisible: false,
      currentItem: null,
      currentType: 1, // 当前选中的图表类型
      currentName: '', // 当前选中的项目名称
      currentChartType: '', // 添加当前图表类型标识
      year: '',
      transferChartOption: {},
      isTransferChart: false,
      showAdvertDialog: false,
      advertData: [],
      totalAreaMoney: 0 // 添加总额数据
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 添加 $nextTick
      this.initCharts()
      // 设置日期选择器的挂载点为特定的容器
      this.appendTo = document.getElementById('date-picker-container')
    })
  },
  created() {
    // 设置默认的日期范围为当年
    const currentYear = new Date().getFullYear()
    const startDate = `${currentYear}-01-01`
    const endDate = `${currentYear}-12-31`

    // 设置默认日期范围
    this.dayRange = [startDate, endDate]

    // 直接调用查询方法
    this.handleSearch()
  },
  beforeDestroy() {
    // 销毁图表实例
    Object.values(this.charts).forEach((chart) => {
      chart.dispose()
    })
  },
  methods: {
    initCharts() {
      this.$nextTick(() => {
        // 添加 $nextTick 确保 DOM 已更新
        try {
          this.loading = true
          this.initDepartmentChart()
          this.initProductChart()
          this.initCustomerChart()
          // this.initPropertyChart();
          this.initStockChart()
          this.initAllMoneyChart()
          this.initCostMoneyChart()
          this.initAreaChart() // 移到最后初始化
          this.initTransferChart()
          this.initProjectFromChart() // 添加新图表初始化
          this.loading = false
        } catch (error) {
          console.error('初始化图表失败:', error)
          this.loading = false
        }
      })
    },
    // 执行部门对应合同金额
    initDepartmentChart(data = []) {
      try {
        if (!this.$refs.departmentChart) {
          console.warn('departmentChart ref not found')
          return
        }

        const chart = echarts.init(this.$refs.departmentChart)
        // 降序排序（金额大的在前）
        const sortedData = [...data].sort((a, b) => b.money - a.money)

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: '{b}: {c}万元',
            position: function(pos, params, dom, rect, size) {
              // 调整提示框位置，确保不遮挡文字
              return [pos[0] + 10, pos[1] - 30]
            }
          },
          grid: {
            left: '30%', // 从25%增加到30%，给左侧文字腾出更多空间
            right: '10%',
            bottom: '3%',
            top: '3%',
            containLabel: false
          },
          xAxis: {
            type: 'value',
            show: false,
            max: function(value) {
              return value.max * 1.15
            }
          },
          yAxis: {
            type: 'category',
            data: sortedData.map((item) => item.name),
            inverse: true, // 反转Y轴，使最大值在顶部
            axisLabel: {
              align: 'right',
              margin: 20,
              color: '#fff',
              fontSize: 15,
              rich: {
                alignRight: {
                  align: 'right',
                  width: 120, // 将宽度从100增加到120，让文字有更多显示空间
                  fontSize: 15
                }
              },
              formatter: function(value) {
                return '{alignRight|' + value + '}'
              }
            },
            axisLine: { show: false },
            axisTick: { show: false }
          },
          series: [
            {
              type: 'bar',
              data: sortedData.map((item) => (item.money / 10000).toFixed(2)),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: '#00FFFF' },
                  { offset: 1, color: '#0080FF' }
                ]),
                borderRadius: [0, 4, 4, 0]
              },
              barWidth: '30%',
              label: {
                show: true,
                position: 'right',
                color: '#fff',
                fontSize: 14,
                formatter: '{c}万元',
                distance: 5
              }
            }
          ]
        }

        chart.setOption(option)

        // 添加点击事件
        this.addHorizontalChartClickEvents(chart, sortedData, 1)

        this.charts.department = chart
      } catch (error) {
        console.error('初始化执行部门图表失败:', error)
      }
    },
    // 横向柱状图的点击事件处理函数
    addHorizontalChartClickEvents(chart, data, chartType) {
      // 柱子点击事件
      chart.on('click', (params) => {
        if (params.componentType === 'series') {
          this.handleItemClick(data[params.dataIndex], chartType)
        }
      })

      // y轴标签和区域点击事件
      chart.getZr().on('click', (params) => {
        const grid = chart.getModel().getComponent('grid').coordinateSystem
        const point = [params.offsetX, params.offsetY]

        if (grid.containPoint(point)) {
          const yIndex = Math.floor(
            chart.convertFromPixel({ yAxisIndex: 0 }, point[1])
          )
          if (yIndex >= 0 && yIndex < data.length) {
            this.handleItemClick(data[yIndex], chartType)
          }
        }
      })
    },
    // 平台产品IP对应合同金额
    initProductChart(data = []) {
      try {
        if (!this.$refs.productChart) {
          console.warn('productChart ref not found')
          return
        }

        const chart = echarts.init(this.$refs.productChart)
        // 降序排序（金额大的在前）
        const sortedData = [...data].sort((a, b) => b.money - a.money)

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: '{b}: {c}万元',
            position: function(pos, params, dom, rect, size) {
              return [pos[0] + 10, pos[1] - 30]
            }
          },
          grid: {
            left: '30%', // 增加左侧空间
            right: '10%',
            bottom: '3%',
            top: '3%',
            containLabel: false
          },
          xAxis: {
            type: 'value',
            show: false,
            max: function(value) {
              return value.max * 1.15
            }
          },
          yAxis: {
            type: 'category',
            data: sortedData.map((item) => item.name),
            inverse: true, // 关键修改：反转Y轴，使第一个数据在顶部显示
            axisLabel: {
              align: 'right',
              margin: 20,
              color: '#fff',
              fontSize: 15, // 改为15px
              rich: {
                alignRight: {
                  align: 'right',
                  width: 120, // 增加宽度
                  fontSize: 15
                }
              },
              formatter: function(value) {
                return '{alignRight|' + value + '}'
              }
            },
            axisLine: { show: false },
            axisTick: { show: false }
          },
          series: [
            {
              type: 'bar',
              data: sortedData.map((item) => (item.money / 10000).toFixed(2)),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: '#00FFFF' },
                  { offset: 1, color: '#0080FF' }
                ]),
                borderRadius: [0, 4, 4, 0]
              },
              barWidth: '30%',
              label: {
                show: true,
                position: 'right',
                color: '#fff',
                fontSize: 14,
                formatter: '{c}万元',
                distance: 5
              }
            }
          ]
        }

        chart.setOption(option)

        // 添加点击事件
        this.addHorizontalChartClickEvents(chart, sortedData, 6)

        window.addEventListener('resize', function() {
          chart.resize()
        })

        this.charts.product = chart
      } catch (error) {
        console.error('初始化平台产品IP图表失败:', error)
      }
    },
    // 项目领域对应合同金额
    initAreaChart(data = []) {
      try {
        if (!this.$refs.areaChart) {
          console.warn('areaChart ref not found')
          return
        }

        const chart = echarts.init(this.$refs.areaChart)

        // 提取第一条数据（总额）并从数组中移除
        const totalData = data.find((item) => item.name === '总额')
        this.totalAreaMoney = totalData
          ? (totalData.money / 10000).toFixed(2) + '万元'
          : '0.00万元' // 设置总额为万元

        // 过滤掉"总额"数据，只展示实际领域
        const chartData = data.filter((item) => item.name !== '总额')
        // 降序排序（金额大的在前）
        const sortedData = [...chartData].sort((a, b) => b.money - a.money)

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: '{b}: {c}万元',
            position: function(pos, params, dom, rect, size) {
              return [pos[0] + 10, pos[1] - 30]
            }
          },
          grid: {
            left: '30%', // 增加左侧空间
            right: '10%',
            bottom: '3%',
            top: '3%',
            containLabel: false
          },
          xAxis: {
            type: 'value',
            show: false,
            max: function(value) {
              return value.max * 1.15
            }
          },
          yAxis: {
            type: 'category',
            data: sortedData.map((item) => item.name),
            inverse: true, // 反转Y轴，使最大值在顶部
            axisLabel: {
              align: 'right',
              margin: 20,
              color: '#fff',
              fontSize: 15,
              rich: {
                alignRight: {
                  align: 'right',
                  width: 120, // 增加宽度
                  fontSize: 15
                }
              },
              formatter: function(value) {
                return '{alignRight|' + value + '}'
              }
            },
            axisLine: { show: false },
            axisTick: { show: false }
          },
          series: [
            {
              type: 'bar',
              data: sortedData.map((item) => (item.money / 10000).toFixed(2)),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: '#00FFFF' },
                  { offset: 1, color: '#0080FF' }
                ]),
                borderRadius: [0, 4, 4, 0]
              },
              barWidth: '30%',
              label: {
                show: true,
                position: 'right',
                color: '#fff',
                fontSize: 14,
                formatter: '{c}万元',
                distance: 5
              }
            }
          ]
        }

        chart.setOption(option)

        // 添加点击事件
        this.addHorizontalChartClickEvents(chart, sortedData, 3)

        this.charts.area = chart
      } catch (error) {
        console.error('初始化项目领域图表失败:', error)
      }
    },
    // 获取详细数据的方法
    async getDetailData(params) {
      try {
        this.loading = true
        const response = await projectDataApi(params)
        if (response && response.code === 200) {
          this.currentItem = {
            name: params.name,
            lists: response.data || []
          }
          this.dialogVisible = true
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取详细数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    // 客户类型对应合同金额
    initCustomerChart(data = []) {
      try {
        if (!this.$refs.customerChart) return
        const chart = echarts.init(this.$refs.customerChart)

        // 对数据进行排序并找出最大值，用于后续判断
        const sortedData = [...data].sort((a, b) => b.money - a.money)
        const maxValue = sortedData.length > 0 ? sortedData[0].money : 0

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: '{b}: {c}万元',
            position: function(pos, params, dom, rect, size) {
              return [pos[0] + 10, pos[1] - 30]
            }
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '15%',
            top: '40%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.map((item) => item.name),
            axisLabel: {
              show: true,
              color: '#fff',
              fontSize: 14,
              interval: 0,
              rotate: 0,
              margin: 20
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.3)'
              }
            }
          },
          yAxis: {
            type: 'value',
            max: function(value) {
              return value.max * 1.1
            },
            axisLabel: { show: false },
            splitLine: {
              show: true,
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.1)',
                type: 'dashed'
              }
            }
          },
          series: [
            {
              type: 'bar',
              data: data.map((item) => (item.money / 10000).toFixed(2)),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: '#00FFFF' },
                  { offset: 1, color: '#0080FF' }
                ]),
                borderRadius: [5, 5, 0, 0]
              },
              barWidth: '30%',
              label: {
                show: true,
                position: 'top',
                color: '#fff',
                fontSize: 12, // 减小柱子顶部数值的字体大小
                formatter: '{c}万元',
                distance: 5
              }
            }
          ]
        }

        chart.setOption(option)
        this.addChartClickEvents(chart, data, 2)
      } catch (error) {
        console.error('初始化客户类型图表失败:', error)
      }
    },
    // 项目属性对应合同金额
    initPropertyChart(data = []) {
      try {
        if (!this.$refs.propertyChart) return
        const chart = echarts.init(this.$refs.propertyChart)
        chart.setOption(this.getVerticalChartOption(data))
        this.addChartClickEvents(chart, data, 4)
      } catch (error) {
        console.error('初始化项目属性图表失败:', error)
      }
    },
    // 存量类型对应合同金额
    initStockChart(data = []) {
      try {
        if (!this.$refs.stockChart) return
        const chart = echarts.init(this.$refs.stockChart)
        const option = this.getVerticalChartOption(data, true) // 添加参数表示使用万元
        chart.setOption(option)
        this.addChartClickEvents(chart, data, 5)
      } catch (error) {
        console.error('初始化存量类型图表失败:', error)
      }
    },
    // 项目金额预览图表
    initAllMoneyChart(data = []) {
      try {
        if (!this.$refs.allMoneyChart) return
        const chart = echarts.init(this.$refs.allMoneyChart)
        const option = this.getVerticalChartOption(data, true) // 添加参数表示使用万元
        chart.setOption(option)
        this.addChartClickEvents(chart, data, 7)
      } catch (error) {
        console.error('初始化合同金额图表失败:', error)
      }
    },
    // 项目成本预览图表
    initCostMoneyChart(data = []) {
      try {
        if (!this.$refs.costMoneyChart) return
        const chart = echarts.init(this.$refs.costMoneyChart)
        const option = this.getVerticalChartOption(data, true) // 添加参数表示使用万元
        chart.setOption(option)
        this.addChartClickEvents(chart, data, 8)
      } catch (error) {
        console.error('初始化项目成本预览图表失败:', error)
      }
    },
    // 统一的图表点击事件处理函数
    addChartClickEvents(chart, data, chartType) {
      // 柱子点击事件
      chart.on('click', (params) => {
        if (params.componentType === 'series') {
          this.handleItemClick(data[params.dataIndex], chartType)
        }
      })

      // 坐标轴标签点击事件
      chart.getZr().on('click', (params) => {
        const grid = chart.getModel().getComponent('grid').coordinateSystem
        const point = [params.offsetX, params.offsetY]

        if (grid.containPoint(point)) {
          const xIndex = Math.floor(
            chart.convertFromPixel({ xAxisIndex: 0 }, point[0])
          )
          if (xIndex >= 0 && xIndex < data.length) {
            this.handleItemClick(data[xIndex], chartType)
          }
        }
      })
    },
    // 查询
    handleSearch() {
      if (!this.dayRange || this.dayRange.length !== 2) {
        this.$message.warning('请选择日期范围')
        return
      }

      const params = {
        startTime: new Date(this.dayRange[0]).getTime(),
        endTime: new Date(this.dayRange[1] + ' 23:59:59').getTime()
      }

      this.loading = true
      Promise.all([
        selCustomerTypeMoneyListApi(params),
        selDepartmentMoneyListApi(params),
        selPlatformMoneyListApi(params),
        selProjectAreaMoneyListApi(params),
        selProjectFromAllMoneyListApi(params),
        selStockTypeMoneyListApi(params),
        selMoneyAndCountApi(params),
        selProjectTypeAllMoneyListApi(params),
        selProjectTypeCostMoneyListApi(params),
        selTransferMoneyListApi(params)
      ])
        .then(
          ([
            customerTypeData,
            departmentData,
            platformData,
            areaData,
            projectFromData,
            stockData,
            totalData,
            allMoneyData,
            costMoneyData,
            transferData
          ]) => {
            this.$nextTick(() => {
              // 确保DOM元素存在再初始化
              if (this.$refs.customerChart && customerTypeData.code === 1) { this.initCustomerChart(customerTypeData.data) }
              if (this.$refs.departmentChart && departmentData.code === 1) { this.initDepartmentChart(departmentData.data) }
              if (this.$refs.productChart && platformData.code === 1) { this.initProductChart(platformData.data) }
              if (stockData.code === 1) this.initStockChart(stockData.data)
              if (allMoneyData.code === 1) { this.initAllMoneyChart(allMoneyData.data) }
              if (costMoneyData.code === 1) { this.initCostMoneyChart(costMoneyData.data) }
              if (areaData.code === 1) this.initAreaChart(areaData.data)
              if (transferData.code === 1) { this.initTransferChart(transferData.data) }
              if (this.$refs.projectFromChart && projectFromData.code === 1) { this.initProjectFromChart(projectFromData.data) }

              // 更新总计数据
              if (totalData.code === 1) {
                this.totalMoney = totalData.data.money || 0
                this.totalCount = totalData.data.count || 0
                this.year = totalData.data.year || ''
              }
            })
          }
        )
        .catch((error) => {
          console.error('查询失败:', error)
          this.$message.error('查询失败，请重试')
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 导出Excel
    async handleExport() {
      // 1. 首先验证是否选择了日期范围
      if (!this.dayRange || this.dayRange.length !== 2) {
        this.$message.warning('请选择日期范围')
        return
      }

      let loading = null
      try {
        // 2. 弹出确认对话框
        await this.$confirm(
          '此操作将导出所选日期范围内的数据, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        // 3. 显示加载中的遮罩层
        loading = this.$loading({
          lock: true,
          text: '正在导出数据,请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        // 4. 准备请求参数，将日期转换为时间戳
        const params = {
          startTime: new Date(this.dayRange[0]).getTime() / 1000,
          endTime: new Date(this.dayRange[1] + ' 23:59:59').getTime() / 1000 // 结束时间设置为当天的最后一秒
        }

        // 5. 调用导出接口
        const res = await dataExcelApi(params)

        // 6. 处理返回结果
        if (res.code === 1 && res.data) {
          // 创建一个临时的a标签来下载文件
          const link = document.createElement('a')
          link.href = res.data
          link.download = '数据分析报表.xlsx'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          this.$message.success('导出成功')
        } else {
          this.$message.error(res.msg || '导出失败')
        }
      } catch (error) {
        // 7. 错误处理（如果不是用户取消导出，则显示错误信息）
        if (error !== 'cancel') {
          console.error('导出错误:', error)
          this.$message.error('导出失败')
        }
      } finally {
        // 8. 无论成功失败，最后都要关闭加载遮罩
        if (loading) {
          loading.close()
        }
      }
    },
    // 格式化数字，添加千位分隔符
    formatNumber(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    getCommonChartOption(data = [], isHorizontal = false) {
      const sortedData = [...data].sort((a, b) => b.money - a.money)

      const baseOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%', // 减小左边距
          right: '4%',
          bottom: '8%',
          top: '8%',
          containLabel: true
        },
        xAxis: {
          type: isHorizontal ? 'value' : 'category',
          data: isHorizontal ? null : sortedData.map((item) => item.name),
          axisLabel: {
            show: !isHorizontal,
            color: '#fff',
            fontSize: 14
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)',
              type: 'dashed'
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)'
            }
          }
        },
        yAxis: {
          type: isHorizontal ? 'category' : 'value',
          data: isHorizontal ? sortedData.map((item) => item.name) : null,
          axisLabel: {
            show: false // 隐藏y轴刻度值
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)',
              type: 'dashed'
            }
          },
          axisLine: {
            show: false // 隐藏y轴线
          },
          axisTick: {
            show: false // 隐藏刻度线
          }
        },
        series: [
          {
            type: 'bar',
            data: sortedData.map((item) => item.money),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(
                0,
                0,
                isHorizontal ? 1 : 0,
                1,
                [
                  { offset: 0, color: '#00FFFF' },
                  { offset: 1, color: '#0080FF' }
                ]
              )
            },
            barWidth: '40%',
            label: {
              show: true,
              position: 'top',
              color: '#fff',
              fontSize: 14,
              formatter: '{c}元'
            }
          }
        ]
      }

      // 针对客户类型、项目属性和存量类型的特殊处理
      if (!isHorizontal) {
        baseOption.yAxis.splitLine.show = false // 隐藏水平分割线
        baseOption.xAxis.axisLabel.interval = 0 // 显示所有x轴标签
        baseOption.xAxis.axisLabel.rotate = 0 // 不旋转标签
      }

      return baseOption
    },
    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 修改点击处理函数
    async handleItemClick(item, chartType) {
      if (!item) return

      this.currentType = chartType
      this.currentName = item.name
      this.currentItem = item
      this.currentChartType = '' // 重置当前图表类型

      // 处理产品合同金额图表中的"广告"项
      if (item.name === '广告' && item.lists) {
        // 构造树形结构数据
        this.advertData = item.lists.map((adItem, parentIndex) => ({
          pname: adItem.name,
          money: adItem.money,
          id: `parent_${Date.now()}_${parentIndex}`, // 父级id使用parent前缀
          // 将内层的 lists 作为 children
          children: adItem.lists.map((subItem, childIndex) => ({
            id: `child_${Date.now()}_${parentIndex}_${childIndex}`, // 子级id使用child前缀
            projectNo: subItem.projectNo || '',
            pname: subItem.pname || '',
            money: subItem.money || 0,
            salesman: subItem.salesman || '',
            customer: subItem.customer || '',
            content: subItem.content || ''
          }))
        }))

        // 显示专门的广告弹窗
        this.showAdvertDialog = true
        return // 提前返回，不执行下面的普通项目逻辑
      }

      // 根据图表类型设置不同的行为
      if (chartType === 4) {
        // 项目采购方式图表
        this.currentChartType = 'projectFrom'
        this.isTransferChart = false
      } else if (chartType === 9) {
        // 划转金额图表
        this.currentChartType = 'transfer'
        this.isTransferChart = true
      } else {
        this.isTransferChart = false
      }

      this.dialogVisible = true
    },
    // 修改广告数据处理方法
    formatAdvertData(data) {
      if (!data || !data.lists) return []

      // 处理成树形结构
      return [
        {
          id: 'root',
          name: data.name,
          money: data.money + '元',
          children: data.lists.map((item, index) => ({
            id: index,
            name: item.name,
            money: item.money + '元'
          }))
        }
      ]
    },
    // 处理详情页面的导出
    async handleDetailExport() {
      if (!this.dayRange || this.dayRange.length !== 2) {
        this.$message.warning('请选择日期范围')
        return
      }

      let loading = null
      try {
        // 修改确认提示框的内容，显示当前选中项的名称
        await this.$confirm(
          `此操作将导出 "${this.currentName}" 的详细数据, 是否继续?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        loading = this.$loading({
          lock: true,
          text: `正在导出 "${this.currentName}" 的数据,请稍候...`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        const params = {
          startTime: new Date(this.dayRange[0]).getTime() / 1000,
          endTime: new Date(this.dayRange[1] + ' 23:59:59').getTime() / 1000,
          type: this.currentType,
          name: this.currentName
        }

        const res = await projectDataApi(params)

        if (res.code === 1 && res.data) {
          const link = document.createElement('a')
          link.href = res.data
          link.download = `${this.currentName}详细数据.xlsx`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          this.$message.success(`${this.currentName}数据导出成功`)
        } else {
          this.$message.error(res.msg || '导出失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('导出错误:', error)
          this.$message.error('导出失败')
        }
      } finally {
        if (loading) {
          loading.close()
        }
      }
    },
    // 添加划转对象图表初始化方法
    initTransferChart(data = []) {
      try {
        if (!this.$refs.transferChart) {
          console.warn('transferChart ref not found')
          return
        }
        const chart = echarts.init(this.$refs.transferChart)

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: '{b}: {c}万元',
            position: function(pos, params, dom, rect, size) {
              return [(size.viewSize[0] - dom.offsetWidth) / 2, 70]
            },
            confine: true,
            extraCssText:
              'z-index: 999; pointer-events: none; background-color: rgba(0,0,0,0.7);'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%', // 增加底部空间以容纳换行的文字
            top: '25%',
            width: 'auto',
            height: '75%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.map((item) => item.name),
            axisLabel: {
              show: true,
              color: '#fff',
              fontSize: 14,
              interval: 0, // 强制显示所有标签
              margin: 15,
              formatter: function(value) {
                // 如果文字长度超过4个字符，则在第4个字符后添加换行符
                if (value.length > 4) {
                  const parts = value.match(/.{1,4}/g)
                  return parts.join('\n')
                }
                return value
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.3)'
              }
            }
          },
          yAxis: {
            type: 'value',
            max: function(value) {
              const gridHeight = 1 - parseFloat('25%') / 100
              const calculatedMax = value.max * (1 / gridHeight)
              return Math.max(calculatedMax, value.max * 1.2)
            },
            axisLabel: { show: false },
            splitLine: {
              show: true,
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.1)',
                type: 'dashed'
              }
            }
          },
          series: [
            {
              type: 'bar',
              data: data.map((item) => (item.money / 10000).toFixed(2)),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: '#00FFFF' },
                  { offset: 1, color: '#0080FF' }
                ])
              },
              barWidth: '30%',
              label: {
                show: true,
                position: 'top',
                color: '#fff',
                fontSize: 14,
                formatter: '{c}万元',
                distance: 10
              }
            }
          ]
        }

        chart.setOption(option)
        this.addChartClickEvents(chart, data, 9)
      } catch (error) {
        console.error('初始化划转对象图表失败:', error)
      }
    },
    // 项目采购方式对应合同金额
    initProjectFromChart(data = []) {
      try {
        if (!this.$refs.projectFromChart) {
          console.warn('projectFromChart ref not found')
          return
        }

        const chart = echarts.init(this.$refs.projectFromChart)
        const sortedData = [...data].sort((a, b) => a.count - b.count)

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: '{b}: {c}个'
          },
          grid: {
            left: '3%',
            right: '3%',
            bottom: '3%',
            top: '3%',
            containLabel: true,
            width: 'auto',
            height: '90%'
          },
          yAxis: {
            type: 'value',
            max: function(value) {
              const gridHeight = 1 - parseFloat('40%') / 100
              const calculatedMax = value.max * (1 / gridHeight)
              return Math.max(calculatedMax, value.max * 1.5)
            },
            axisLabel: {
              show: false
            },
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: {
              show: true,
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.1)',
                type: 'dashed',
                width: 1
              }
            },
            splitArea: {
              show: true,
              areaStyle: {
                color: 'transparent'
              }
            },
            boundaryGap: [0, '0%']
          },
          xAxis: {
            type: 'category',
            data: sortedData.map((item) => item.name),
            axisLabel: {
              interval: 0,
              color: '#fff',
              fontSize: 14,
              formatter: function(value) {
                const length = value.length
                if (length > 3) {
                  if (length === 4) {
                    // 4个字：2 + 2
                    return `${value.substring(0, 2)}\n${value.substring(2)}`
                  } else if (length === 5) {
                    // 5个字：2 + 3
                    return `${value.substring(0, 2)}\n${value.substring(2)}`
                  } else if (length === 6) {
                    // 6个字：3 + 3
                    return `${value.substring(0, 3)}\n${value.substring(3)}`
                  } else {
                    // 超过6个字：按3字一组换行
                    const parts = value.match(/.{1,3}/g)
                    return parts.join('\n')
                  }
                }
                // 不超过3个字，直接返回
                return value
              }
            },
            axisLine: { show: false },
            axisTick: { show: false }
          },
          series: [
            {
              type: 'bar',
              data: sortedData.map((item) => item.count),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: '#00FFFF' },
                  { offset: 1, color: '#0080FF' }
                ])
              },
              barWidth: '15%',
              label: {
                show: true,
                position: 'top',
                color: '#fff',
                fontSize: 14,
                formatter: '{c}个'
              }
            }
          ]
        }

        chart.setOption(option)

        // 添加点击事件处理
        chart.on('click', (params) => {
          if (params.componentType === 'series') {
            this.handleItemClick(sortedData[params.dataIndex], 4)
          }
        })

        // 添加坐标轴标签点击事件
        chart.getZr().on('click', (params) => {
          const grid = chart.getModel().getComponent('grid').coordinateSystem
          const point = [params.offsetX, params.offsetY]

          if (grid.containPoint(point)) {
            const xIndex = Math.floor(
              chart.convertFromPixel({ xAxisIndex: 0 }, point[0])
            )
            if (xIndex >= 0 && xIndex < sortedData.length) {
              this.handleItemClick(sortedData[xIndex], 4)
            }
          }
        })

        this.charts.projectFrom = chart
      } catch (error) {
        console.error('初始化项目采购方式图表失败:', error)
      }
    },
    handleChartClick(type) {
      console.log('Chart type clicked:', type)
      this.currentChartType = type
      this.isTransferChart = type === 'transfer'
      console.log('isTransferChart:', this.isTransferChart)
    },
    // 修改弹框关闭处理方法
    handleDialogClose() {
      this.isTransferChart = false // 关闭弹框时重置 isTransferChart
      this.dialogVisible = false
    },
    // 修改所有垂直柱状图的配置
    getVerticalChartOption(data, useWanYuan = false, isCost = false) {
      const maxValue = Math.max(...data.map((item) => item.money))
      const gridTop = '25%' // 标题区域的高度比例

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: useWanYuan ? '{b}: {c}万元' : '{b}: {c}元',
          position: function(pos, params, dom, rect, size) {
            return [(size.viewSize[0] - dom.offsetWidth) / 2, 70]
          },
          confine: true,
          extraCssText:
            'z-index: 999; pointer-events: none; background-color: rgba(0,0,0,0.7);'
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '15%',
          top: '25%', // 保持一致的顶部空间
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map((item) => item.name),
          axisLabel: {
            show: true,
            color: '#fff',
            fontSize: 14
          }
        },
        yAxis: {
          type: 'value',
          max: function(value) {
            const gridHeight = 1 - parseFloat(gridTop) / 100
            const calculatedMax = value.max * (1 / gridHeight)
            return Math.max(calculatedMax, value.max * 1.2)
          },
          axisLabel: { show: false },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            type: 'bar',
            data: useWanYuan
              ? data.map((item) => (item.money / 10000).toFixed(2))
              : data.map((item) => item.money),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: '#00FFFF' },
                { offset: 1, color: '#0080FF' }
              ])
            },
            barWidth: '30%',
            label: {
              show: true,
              position: 'top',
              color: '#fff',
              fontSize: 14,
              formatter: useWanYuan ? '{c}万元' : '{c}元',
              distance: 10
            }
          }
        ]
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #001b4a 0%, #000b2c 100%);
  background-image: url("~@/assets/images/数据可视化背景图.jpg");
  // background-image: url("~@/assets/images/数据可视化背景图.gif");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  padding: 20px;
  color: #fff;
  position: relative;
}

.dashboard-container::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 11, 44, 0.3); // 降低遮罩不透明度
  pointer-events: none;
}

.dashboard-container > * {
  position: relative;
  z-index: 1;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 30px;
  font-weight: bold;
  transform: translate(370px, 0px);
}

.search-area {
  display: flex;
  align-items: center;
}

.main-content {
  display: flex;
  gap: 10px; // 减小列之间的间距
  margin-top: 10px; // 减小顶部边距
  padding: 0;
  list-style: none;
  height: calc(100vh);
}

.content-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px; // 减小图表之间的垂直间距
}

.chart-box {
  flex: 1;
  background: rgba(3, 22, 95, -1.7); // 浅蓝色背景
  border: 1px solid rgba(0, 255, 255, 0.15);
  box-shadow: 0 0 20px rgba(0, 255, 255, 0.1);
  border-radius: 4px;
  padding: 10px 10px; // 减小上下内边距，保持左右内边距
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(5px);
  position: relative;
  overflow: hidden;
  margin-bottom: 10px; // 减小底部外边距

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 5px; // 减小标题和内容之间的间距
    padding-right: 20px;
  }

  .total-amount {
    display: flex;
    align-items: center;
    white-space: nowrap;
    margin-bottom: 5px; // 减小总金额和图表之间的间距

    .total-label {
      font-size: 16px;
      font-weight: bold;
      color: #fff;
      margin-right: 4px;
      position: relative;
      top: 2px;
    }

    .value-wrapper {
      position: relative;
      top: -2px;
    }

    .total-value {
      color: #fff;
      font-size: 16px;
      font-weight: bold;
    }
  }

  .chart-title {
    display: flex;
    align-items: center;
    margin-bottom: 5px; // 减小标题下方间距
  }

  // 减小图表组件自身的内边距
  .chart {
    padding-top: 0;
    padding-bottom: 0;
  }
}

.chart-box:hover {
  background: rgba(3, 22, 95, 0.4); // hover时稍微加深
  border-color: rgba(0, 255, 255, 0.3);
  box-shadow: 0 0 30px rgba(0, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.chart {
  flex: 1;
  height: 100%;
}

.total-info {
  // background: rgba(3, 22, 95, 0.3); // 与图表块保持一致
  background: rgba(3, 22, 95, -1.7); // 与图表块保持一致
  border: 1px solid rgba(0, 255, 255, 0.15);
  box-shadow: 0 0 20px rgba(0, 255, 255, 0.1);
  border-radius: 4px;
  padding: 20px;
}

.total-row {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.total-item {
  text-align: center;
}

.total-label {
  font-size: 20px;
  color: #fff;
  margin-bottom: 10px;
}

.total-value {
  display: flex;
  align-items: baseline;
  justify-content: center;

  .number {
    font-size: 36px;
    font-weight: bold;
    color: #ffd700;
    margin-right: 8px;
  }

  .unit {
    font-size: 18px;
    color: #fff;
  }
}

.chart-title {
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 16px;
  margin-bottom: 15px;
}

.chart-icon {
  display: inline-block;
  width: 4px;
  height: 16px;
  background: #1890ff;
  margin-right: 5px; // 减小右边距
  border-radius: 2px;
}

.label {
  color: #fff;
  margin-right: 10px;
}

:deep(.el-select),
:deep(.el-input),
:deep(.el-button) {
  margin-left: 10px;
}

:deep(.el-input__inner) {
  background: transparent;
  border-color: rgba(255, 255, 255, 0.1);
  color: #fff;
}

:deep(.el-button) {
  background: #1890ff;
  border-color: #1890ff;
}

:deep(.el-button:hover) {
  background: #40a9ff;
  border-color: #40a9ff;
}

.charts-row {
  display: flex;
  gap: 10px; // 减小同一行中图表之间的间距
  flex: 1;
  margin-bottom: 0; // 移除底部边距
}

.charts-row .chart-box {
  flex: 1;
  margin-bottom: 0;
}

.chart {
  height: 300px;
}

/* 项目领域图表特殊高度 */
.chart-box:not(.charts-row .chart-box) .chart {
  height: 400px;
}

:deep(.el-select-dropdown__item) {
  color: #333;
}

:deep(.el-select-dropdown) {
  background-color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.el-select-dropdown__item.hover) {
  background-color: rgba(24, 144, 255, 0.1);
}

:deep(.el-select-dropdown__item.selected) {
  color: #1890ff;
  font-weight: bold;
}

:deep(.el-date-editor.el-input),
:deep(.el-date-editor--daterange) {
  --el-datepicker-border-color: rgba(255, 255, 255, 0.1);
  --el-datepicker-text-color: #fff;
  --el-datepicker-off-text-color: #666;
  --el-datepicker-header-text-color: #fff;
  --el-datepicker-icon-color: #fff;
  --el-datepicker-inner-border-color: rgba(255, 255, 255, 0.1);
  --el-datepicker-inrange-bg-color: rgba(24, 144, 255, 0.1);
  --el-datepicker-inrange-hover-bg-color: rgba(24, 144, 255, 0.2);
  --el-datepicker-active-color: #1890ff;
  --el-datepicker-hover-text-color: #1890ff;
}

:deep(.el-date-editor .el-input__wrapper),
:deep(.el-date-editor.el-input__wrapper) {
  background: transparent;
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1);
}

:deep(.el-date-editor .el-range-separator) {
  color: #fff;
}

:deep(.el-date-editor .el-range-input) {
  color: #fff;
  background: transparent;
}

:deep(.el-picker-panel) {
  background-color: #001b4a;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.el-date-picker__header) {
  color: #fff;
}

:deep(.el-date-picker__header-label) {
  color: #fff;
}

:deep(.el-date-table th) {
  color: #fff;
}

:deep(.el-date-table td.available:hover) {
  color: #1890ff;
}

:deep(.el-date-table td.current:not(.disabled)) {
  background-color: #1890ff;
  color: #fff;
}

:deep(.el-date-table td.in-range) {
  background-color: rgba(24, 144, 255, 0.1);
}

:deep(.el-date-table td.end-date .el-date-table-cell__text),
:deep(.el-date-table td.start-date .el-date-table-cell__text) {
  background-color: #1890ff;
}

:deep(.date-picker-popper .el-picker-panel__body) {
  background: #001b4a;
}

:deep(.date-picker-popper .el-date-range-picker__header) {
  color: #fff;
}

:deep(.date-picker-popper .el-date-range-picker__content) {
  background: #001b4a;
}

:deep(.date-picker-popper .el-date-table th) {
  color: #fff;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.date-picker-popper .el-date-table td) {
  background: transparent;
}

:deep(.date-picker-popper .el-date-table td.available:hover) {
  color: #1890ff;
}

:deep(.date-picker-popper .el-date-table td.in-range div) {
  background-color: rgba(24, 144, 255, 0.1);
}

:deep(
    .date-picker-popper .el-date-table td.end-date div,
    .date-picker-popper .el-date-table td.start-date div
  ) {
  background-color: #1890ff;
  color: #fff;
}

:deep(.date-picker-popper .el-date-range-picker__content.is-left) {
  border-right: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.el-picker-panel__icon-btn) {
  color: #fff;
}

:deep(.el-picker-panel.el-date-range-picker) {
  background-color: #001b4a !important;
}

:deep(.el-date-range-picker__header) {
  margin: 0 !important;
  padding: 12px 20px !important;
  color: #fff !important;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-date-range-picker__content) {
  padding: 10px !important;
}

:deep(.el-date-range-picker__content.is-left) {
  border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-date-table th) {
  padding: 5px !important;
  color: #fff !important;
  font-weight: 400 !important;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-date-table td.available:hover) {
  color: #1890ff !important;
}

:deep(.el-date-table td.in-range div) {
  background-color: rgba(24, 144, 255, 0.1) !important;
  color: #fff !important;
}

:deep(.el-date-table td.end-date div, .el-date-table td.start-date div) {
  background-color: #1890ff !important;
  color: #fff !important;
}

:deep(.el-picker-panel__icon-btn) {
  color: #fff !important;
}

:deep(.el-date-range-picker__header div) {
  color: #fff !important;
}

:deep(.el-date-table td.next-month, .el-date-table td.prev-month) {
  color: #606266 !important;
}

:deep(.el-date-range-picker__content) {
  background-color: #001b4a !important;
}

.dialog-header {
  text-align: right;
  margin-bottom: 20px;
}

#date-picker-container {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2000;
}

/* 日期选择器样式 */
:deep(.date-picker-popper) {
  position: fixed !important;
  background-color: #001b4a !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: #fff !important;
}

:deep(.el-picker-panel) {
  background: #001b4a !important;
}

:deep(.el-date-range-picker__header) {
  color: #fff !important;
}

:deep(.el-date-range-picker__content) {
  background: #001b4a !important;
}

:deep(.el-date-table th) {
  color: #fff !important;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-date-table td) {
  color: #fff !important;
}

:deep(.el-date-table td.next-month, .el-date-table td.prev-month) {
  color: #606266 !important;
}

:deep(.el-date-table td.available:hover) {
  color: #1890ff !important;
}

:deep(.el-date-table td.in-range div) {
  background-color: rgba(24, 144, 255, 0.1) !important;
  color: #fff !important;
}

:deep(.el-date-table td.end-date div, .el-date-table td.start-date div) {
  background-color: #1890ff !important;
  color: #fff !important;
}

:deep(.el-date-range-picker__content.is-left) {
  border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-picker-panel__icon-btn) {
  color: #fff !important;
}

:deep(.el-date-range-picker__header div) {
  color: #fff !important;
}

/* 自定义 loading 样式 */
// /deep/ .el-loading-spinner {
//   .el-loading-text {
//     color: #fff;
//     font-size: 14px;
//   }

//   .el-icon-loading {
//     font-size: 30px;
//     color: #409eff;
//   }
// }

/* 添加特定的类名来控制这两个图表的容器 */
.department-chart,
.product-chart {
  // margin-left: -80px; // 向左偏移
  // width: calc(100% + 80px); // 补偿宽度
}

.horizontal-chart-wrapper {
  position: relative;
  width: 100%;
  margin-left: -100px; // 减小向左偏移量
  .chart {
    width: calc(100% + 100px); // 相应调整补偿宽度
  }
}

.todo-content {
  cursor: pointer; // 移除鼠标手型样式，因为整行都可以点击
}

// 添加表格行悬停效果
:deep(.el-table__row) {
  cursor: pointer;

  &:hover {
    background-color: rgba(24, 144, 255, 0.1);
  }
}

.area-chart {
  margin-top: 0;
  width: 100%;
  height: 350px; // 调整整体高度
  background: rgba(1, 19, 67, 0.8);
  border-radius: 4px;
  padding: 20px;

  .chart {
    height: calc(100% - 30px);
    margin-top: 10px;
  }

  .chart-title {
    height: 30px;
    line-height: 30px;
    margin-bottom: 0;
  }
}

.chart {
  width: 100%;
  height: 100%;
}

/* 移除不需要的样式 */
.area-chart {
  margin-top: 0;
}

/* 确保图表行之间有适当的间距 */
.charts-row {
  // margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

/* 添加弹窗相关样式 */
.el-dialog {
  .el-table {
    margin-top: 20px;

    // 自定义表格样式
    ::v-deep .el-table__row {
      background-color: #fff;
    }

    // 树形图标样式
    ::v-deep .el-table__expand-icon {
      color: #409eff;
    }
  }
}

// 添加内部发光效果
.chart-box::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  background: radial-gradient(
    circle at 50% 50%,
    rgba(0, 255, 255, 0.05),
    transparent 70%
  );
}

/* 添加或修改弹框样式 */
:deep(.el-dialog__wrapper) {
  display: flex;
  align-items: center !important; // 垂直居中
  justify-content: center !important; // 水平居中
}

:deep(.el-dialog) {
  margin: 0 !important; // 清除默认margin
  position: relative;
  background: rgba(3, 22, 95, 0.9);
  border: 1px solid rgba(0, 255, 255, 0.15);
  box-shadow: 0 0 20px rgba(0, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

:deep(.el-dialog__header) {
  background: rgba(3, 22, 95, 0.8);
  padding: 15px 20px;
  border-bottom: 1px solid rgba(0, 255, 255, 0.1);
}

:deep(.el-dialog__title) {
  color: #fff;
  font-size: 16px;
}

:deep(.el-dialog__body) {
  color: #fff;
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid rgba(0, 255, 255, 0.1);
  padding: 15px 20px;
}

/* 自定义滚动条样式 */
:deep(.el-dialog__body)::-webkit-scrollbar {
  width: 6px;
}

:deep(.el-dialog__body)::-webkit-scrollbar-thumb {
  background: rgba(0, 255, 255, 0.2);
  border-radius: 3px;
}

:deep(.el-dialog__body)::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
}

/* 确保弹框在其他元素之上 */
:deep(.el-dialog__wrapper) {
  z-index: 2000 !important;
}

/* 确保遮罩层在弹框之下 */
:deep(.v-modal) {
  z-index: 1999 !important;
}

/* 优化弹框动画 */
:deep(.el-dialog) {
  transform: none;
  opacity: 1;
  transition: all 0.3s ease-in-out;
}

/* 弹框出现时的动画 */
:deep(.el-dialog-fade-enter-active) {
  animation: dialog-fade-in 0.3s;
}

/* 弹框关闭时的动画 */
:deep(.el-dialog-fade-leave-active) {
  animation: dialog-fade-out 0.3s;
}

@keyframes dialog-fade-in {
  0% {
    transform: translate3d(0, -20px, 0);
    opacity: 0;
  }
  100% {
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
}

@keyframes dialog-fade-out {
  0% {
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
  100% {
    transform: translate3d(0, -20px, 0);
    opacity: 0;
  }
}

/* 添加独占一行的图表样式 */
.full-width-chart {
  width: 100%;
  margin-top: 20px;

  .project-from-chart {
    height: 300px;
  }
}
</style>
